<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.min.css';
import { INTERVIEW_PASSWORD } from '@/constants/config';
import useProhibit from '@/stores/prohibit';

const router = useRouter();
const stores = useProhibit();
const { prohibit } = storeToRefs(stores);

// 渲染 markdown 的ref
const markdownRef = ref();

// 处理渲染markdown
const handleRenderMarkdown = async () => {
	if (!markdownRef.value) return;
	// Markdown 源码
	const lastSegment = window.location.pathname.split('/').pop();
	const markdown = await import(`./${lastSegment}/README.md?raw`);
	const markdownSource = markdown.default;

	// 初始化 markdown-it
	const md: MarkdownIt = new MarkdownIt({
		html: true,
		highlight: (str, lang) => {
			if (lang && hljs.getLanguage(lang)) {
				try {
					return '<pre class="hljs"><code>' + hljs.highlight(lang, str, true).value + '</code></pre>';
				} catch (__) {}
			}

			return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
		},
	});

	// 渲染 Markdown
	const renderedMarkdown = md.render(markdownSource);

	// 将渲染后的内容插入到 vueRef 中
	markdownRef.value.innerHTML = renderedMarkdown;
};

// 密码
const password = ref('');
// 点击回车
const handleKeyupEnter = () => {
	if (password.value !== INTERVIEW_PASSWORD) return ElMessage.error('密码错误');
	prohibit.value.password = password.value;
	handleRenderMarkdown();
	setTimeout(() => {
		prohibit.value.isHide = false;
	}, 1000);
};

onMounted(() => {
	if (prohibit.value.isHide) return;
	handleRenderMarkdown();
});

// 监听url变化
watch(
	() => router.currentRoute.value,
	() => {
		if (prohibit.value.isHide) return;
		handleRenderMarkdown();
	}
);
</script>

<template>
	<div class="prohibit">
		<div
			v-if="prohibit.isHide"
			class="prohibit-top"
			:class="prohibit.password === INTERVIEW_PASSWORD && 'prohibit-top-hide'"
		></div>
		<div
			v-if="prohibit.isHide"
			class="prohibit-bottom"
			:class="prohibit.password === INTERVIEW_PASSWORD && 'prohibit-bottom-hide'"
		>
			<el-input
				v-model="password"
				type="password"
				placeholder="输入专区密码"
				maxlength="10"
				show-password
				@keyup.enter="handleKeyupEnter"
			></el-input>
		</div>
		<div ref="markdownRef" class="markdown"></div>
	</div>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
